import { PAGE_TYPE } from '@/common/const'
import { EventBus } from '@/store/index'
import { getCompIdByParam } from '@/plugins/utils'

class Touchmove {
  static isForbid = true;
  static isFirst = true;
}
export const pageCommon = {
  methods: {
    isForbidMove(isForbid){
      Touchmove.isForbid = isForbid;
      
      //长页或是单页中的滚动文本
      if(this.siteAttrs.pageType == PAGE_TYPE.long || this.currentPage.isDisplayTextScroller){
        Touchmove.isFirst = false;
        return
      }

      function preventEventDefault(e){
        e.stopPropagation();
        if(Touchmove.isForbid){
          e.preventDefault();
        }
      }
      //禁止safari下拉反弹页面
      if(Touchmove.isFirst){
        Touchmove.isFirst = false;
        window.addEventListener('touchmove', preventEventDefault, { passive: false });
      }
    },
    isFixIosForm(){
      if(this.currentPage.isForm){
        if(this.siteInfo.md.isMobile && this.siteAttrs.pageType == PAGE_TYPE.single){
          this.iosFormBugFix();
        }
      }
    },
    iosFormBugFix(){
      this.inputOnBlurCb = window.setInterval(() => {
        let inputs = document.querySelectorAll("input");
        let textareas = document.querySelectorAll("textarea");
        inputs = _.concat(Array.prototype.slice.call(inputs), Array.prototype.slice.call(textareas));
        if(inputs.length > 0){
          window.clearInterval(this.inputOnBlurCb)
          _.forEach(inputs, (input) => {
            input.onblur = null;
            input.onblur = () => {
              window.setTimeout( () => {
                window.scrollTo({top: 0, behavior: 'instant'});
              }, 100)
            }
          })
        }
      }, this.siteInfo.reloadTime)
    },
    autoTriggerEvent(){
      let triggerEventTimeAndCompId = this.currentPage.attrs.triggerEventTimeAndCompId;
      if(triggerEventTimeAndCompId){
        let timeAndCompId = triggerEventTimeAndCompId.split(',');
        let time = parseFloat(timeAndCompId[0]);
        let compId = getCompIdByParam(timeAndCompId[1]);
        if(compId){
          window.clearTimeout(this.pageTimer);
          const delayTime = time * 1000 || 1000;
          this.pageTimer = window.setTimeout(() => {
            EventBus.$emit("itemClick", {id: compId, index: 0, e: null});
          }, delayTime);
        }
      }
    }
  }
}